﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Content;
using Tesla.Core;
using Tesla.Math;

namespace Tesla.Graphics {
    /// <summary>
    /// Represents the organization of vertex data in a vertex buffer, which is used by
    /// the device to process the vertex stream.
    /// </summary>
    public sealed class VertexDeclaration : ISavable {
        private VertexElement[] _elements;
        private int _vertexStride;
        private int _hashCode = 0;
        private bool _hashComputed = false;

        /// <summary>
        /// Gets a copy of the contained vertex elements.
        /// </summary>
        public VertexElement[] VertexElements {
            get {
                return (VertexElement[])_elements.Clone();
            }
        }

        /// <summary>
        /// Gets the number of vertex elements contained in this declaration.
        /// </summary>
        public int ElementCount {
            get {
                return _elements.Length;
            }
        }

        /// <summary>
        /// Gets a vertex element at the specified index.
        /// </summary>
        /// <param name="index">Zero-based index of the element</param>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the index is out of range.</exception>
        /// <returns>The vertex element</returns>
        public VertexElement this[int index] {
            get {
                if(index < 0 || index >= _elements.Length) {
                    throw new ArgumentOutOfRangeException("index", "Index out of range.");
                }

                return _elements[index];
            }
        }

        /// <summary>
        /// Gets the stride of a vertex, this is the total size of a vertex (position, color, etc)
        /// in bytes.
        /// </summary>
        public int VertexStride {
            get {
                return _vertexStride;
            }
        }

        /// <summary>
        /// For ISavable.
        /// </summary>
        private VertexDeclaration() {}


        /// <summary>
        /// Creates a new instance of <see cref="VertexDeclaration"/>.
        /// </summary>
        /// <param name="elements">The array of vertex elements that define the vertex.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the vertex elements are null.</exception>
        /// <exception cref="System.ArgumentException">Thrown if the vertex elements are invalid.</exception>
        public VertexDeclaration(params VertexElement[] elements) {
            if(elements == null || elements.Length == 0){
                throw new ArgumentNullException("Vertex Elements must exist.");
            }
            _elements = (VertexElement[]) elements.Clone();
            _vertexStride = GetVertexStride(_elements);

            try {
                ValidateVertexElements(_vertexStride, _elements);
            } catch(Exception e) {
                throw new TeslaException("Failed to validate the vertex declaration: \n" + e.Message, e);
            }

            GetHashCode();
        }

        /// <summary>
        /// Creates a new instance of <see cref="VertexDeclaration"/>.
        /// </summary>
        /// <param name="vertexStride">The vertex stride.</param>
        /// <param name="elements">The array of vertex elements that define the vertex.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the vertex elements are null.</exception>
        /// <exception cref="System.ArgumentException">Thrown if the vertex elements are invalid.</exception>
        public VertexDeclaration(int vertexStride, params VertexElement[] elements) {
            if(elements == null || elements.Length == 0) {
                throw new ArgumentException("Vertex Elements must exist.");
            }
            _elements = (VertexElement[]) elements.Clone();
            _vertexStride = vertexStride;

            try {
                ValidateVertexElements(_vertexStride, _elements);
            } catch(Exception e) {
                throw new TeslaException("Failed to validate the vertex declaration: \n" + e.Message, e);
            }

            GetHashCode();
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>A hash code for this instance.</returns>
        public override int GetHashCode() {
            if(!_hashComputed) {
                int hash = _vertexStride;
                for(int i = 0; i < _elements.Length; i++) {
                    hash = ((hash << 3) - hash) + _elements[i].GetHashCode();
                }
                _hashCode = hash;
                _hashComputed = true;
            }
            return _hashCode;
        }

        /// <summary>
        /// Checks if the array of vertex elements is valid.
        /// </summary>
        /// <param name="vertexStride">Total size in bytes of the vertex elements</param>
        /// <param name="elements">Vertex elements</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the elements array is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the vertex stride is less than zero, or a vertex element
        /// is outside the stride.</exception>
        /// <exception cref="System.ArgumentException">Thrown if the vertex stride or an element offset is not a multiply of four,
        /// or if duplicate vertex elements are found, or if two vertex elements overlap.</exception>
        public static void ValidateVertexElements(int vertexStride, params VertexElement[] elements) {
            
            if(elements == null || elements.Length < 0) {
                throw new ArgumentNullException("Vertex element array is null.");
            }

            if(vertexStride <= 0) {
                throw new ArgumentOutOfRangeException("Vertex stride cannot be less than or equal to 0.");
            }

            if((vertexStride & 3) != 0) {
                throw new ArgumentException("Vertex stride must be a multiple of 4.");
            }

            int expectedStride = 0;
            for(int i = 0; i < elements.Length; i++) {
                VertexElement elem = elements[i];
                int offset = elem.Offset;
                int elemSize = GetVertexElementSize(elem.Format);
                //Ensure offset is multiple of four
                if((offset & 3) != 0) {
                    throw new ArgumentException(String.Format("Vertex element offset is not multiple of four: {0}", elem));
                }
                //Make sure the offset in the element doesn't put us out of range
                if(offset < 0 || (offset + elemSize) > vertexStride) {
                    throw new ArgumentOutOfRangeException(String.Format("Vertex element outside of the vertex stride: {0}", elem));
                }
                //Check previous elements if the current one is a duplicate
                for(int j = 0; j < i; j++) {
                    VertexElement prev = elements[j];
                    if(prev.SemanticName == elem.SemanticName && prev.SemanticIndex == elem.SemanticIndex) {
                        throw new ArgumentException(String.Format("Duplicate vertex elements found for: SemanticName: {0}, SemanticIndex: {1}", new Object[] { prev.SemanticName, prev.SemanticIndex}));
                    }
                }
                //Check for overlap between this element and the previous
                if((expectedStride + elemSize) != (offset + elemSize)) {
                    throw new ArgumentException("Vertex element overlap found, check offsets");
                }

                expectedStride = offset + elemSize;
            }
        }

        /// <summary>
        /// Gets the vertex stride of the specified elements.
        /// </summary>
        /// <param name="elements">The array of vertex elements.</param>
        /// <returns>Total size, in bytes, of the vertex.</returns>
        public static int GetVertexStride(VertexElement[] elements) {
            int stride = 0;
            for(int i = 0; i < elements.Length; i++) {
                int sum = elements[i].Offset + GetVertexElementSize(elements[i].Format);
                if(stride < sum) {
                    stride = sum;
                }
            }
            return stride;
        }

        /// <summary>
        /// Gets the size of a vertex element.
        /// </summary>
        /// <param name="format">Format to query the size of</param>
        /// <returns>Size of the format, in bytes</returns>
        public static int GetVertexElementSize(VertexFormat format) {
            switch(format) {
                case VertexFormat.Single:
                    return sizeof(float);
                case VertexFormat.Vector2:
                    return Vector2.SizeInBytes;
                case VertexFormat.Vector3:
                    return Vector3.SizeInBytes;
                case VertexFormat.Vector4:
                    return Vector4.SizeInBytes;
                case VertexFormat.Color:
                    return Color.SizeInBytes;
                default:
                    return 0;
            }
        }

        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public void Write(ISavableWriter output) {
            output.Write("VertexStride", _vertexStride);
            output.Write("ElementCount", _elements.Length);
            for(int i = 0; i < _elements.Length; i++) {
                VertexElement element = _elements[i];
                output.WriteEnum<VertexSemantic>("SemanticName", element.SemanticName);
                output.Write("SemanticIndex", element.SemanticIndex);
                output.WriteEnum<VertexFormat>("Format", element.Format);
                output.Write("Offset", element.Offset);
            }
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        public void Read(ISavableReader input) {
            _vertexStride = input.ReadInt();
            int count = input.ReadInt();
            _elements = new VertexElement[count];
            for(int i = 0; i < count; i++) {
                VertexSemantic semantic = input.ReadEnum<VertexSemantic>();
                int semanticIndex = input.ReadInt();
                VertexFormat format = input.ReadEnum<VertexFormat>();
                int offset = input.ReadInt();
                _elements[i] = new VertexElement(semantic, semanticIndex, format, offset);
            }
            GetHashCode();
        }
    }
}
